package org.csu.agrisupply.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.csu.agrisupply.api.common.CommonResponse;
import org.csu.agrisupply.api.entity.Farmer;
import org.csu.agrisupply.api.entity.RC;
import org.csu.agrisupply.api.entity.User;
import org.csu.agrisupply.api.persistence.FarmerMapper;
import org.csu.agrisupply.api.persistence.RCMapper;
import org.csu.agrisupply.api.persistence.UserMapper;
import org.csu.agrisupply.api.service.RCService;
import org.csu.agrisupply.api.vo.RCVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("RCService")
public class RCServiceImpl implements RCService {
    @Autowired
    private RCMapper rcMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FarmerMapper farmerMapper;

    @Override
    public CommonResponse<List<RCVo>> getRCList() {
        List<RC> rcList = rcMapper.selectList(null);
        if (rcList.isEmpty()) {
            return CommonResponse.createForSuccessMessages("没有分类信息");
        }
        List<RCVo> rcVoList = new ArrayList<>();
        for (RC item : rcList){
            rcVoList.add(RCtoRCVo(item));
        }
        return CommonResponse.createForSuccess(rcVoList);
    }

    @Override
    public CommonResponse<RCVo> getRC(String rcId) {
        RC rc = rcMapper.selectById(rcId);
        if (rc == null) {
            return CommonResponse.createForSuccessMessages("没有该ID的合作社");
        }
        return CommonResponse.createForSuccess(RCtoRCVo(rc));
    }

    @Override
    public CommonResponse<RC> updateRC(String rcId, RC newrc) {
        RC rc = rcMapper.selectById(rcId);
        if (rc == null) {
            return CommonResponse.createForSuccessMessages("没有该ID的合作社");
        }
        rc = newrc;
        rcMapper.updateById(rc);
        return CommonResponse.createForSuccess("修改成功", rc);
    }

    @Override
    public CommonResponse<RC> registerRC(String userId, RC rc) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return CommonResponse.createForSuccessMessages("没有该ID的user");
        }
        Farmer farmer = farmerMapper.selectById(userId);
        if (farmer == null) {
            return CommonResponse.createForSuccessMessages("该用户不是farmer，不可以注册合作社");
        } else if (!farmer.getRcId().isEmpty()) {
            return CommonResponse.createForSuccessMessages("该farmer已经加入了合作社！不可再注册新的合作社");
        }
        //插入新的合作社到RC表中
        rc.setRcid(getMax());
        rc.setFarmerNumber(1);
        rcMapper.insert(rc);
        //更新farmer表中的数据
        farmer.setRcId(rc.getRcid());
        farmerMapper.updateById(farmer);
        //更新用户角色
        user.setRole(2);
        userMapper.updateById(user);
        return CommonResponse.createForSuccess("注册成功", rc);
    }

    @Override
    public CommonResponse<RC> inviteUsertoRC(String userId, String inviteUserId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return CommonResponse.createForSuccessMessages("没有邀请人ID的user");
        } else if (user.getRole() != 2) {
            return CommonResponse.createForSuccessMessages("邀请人不是合作社管理员不可以进行农户邀请");
        }
        User inviteuser = userMapper.selectById(inviteUserId);
        if (inviteuser == null) {
            return CommonResponse.createForSuccessMessages("没有被邀请人ID的user");
        }
        Farmer farmer = farmerMapper.selectById(inviteUserId);
        if (farmer == null) {
            return CommonResponse.createForSuccessMessages("被邀请人不是farmer，不可以加入合作社");
        } else if (!farmer.getRcId().isEmpty()) {
            return CommonResponse.createForSuccessMessages("被邀请人已经加入了合作社，不可以再次加入另外的合作社");
        }
        RC rc = rcMapper.selectById(farmerMapper.selectById(userId).getRcId());
        //更新farmer表中的rcId
        farmer.setRcId(rc.getRcid());
        farmerMapper.updateById(farmer);
        //rc表中的合作社人数加1
        rc.setFarmerNumber(rc.getFarmerNumber() + 1);
        rcMapper.updateById(rc);
        return CommonResponse.createForSuccessMessages("用户" + inviteuser.getUsername() + "成功加入了" + rc.getName() + "合作社");
    }

    public String getMax() {
        QueryWrapper<RC> wrapper = new QueryWrapper<>();
        wrapper.select("rcId");
        List<Object> rcList = rcMapper.selectObjs(wrapper);
        int Max = 0;
        if (!rcList.isEmpty()) {
            Max = Integer.parseInt(rcList.get(0).toString());
            for (Object item : rcList) {
                int num = Integer.parseInt(item.toString());
                if (num >= Max)
                    Max = num;
            }
        }
        return Integer.toString(Max + 1);
    }

    @Override
    public CommonResponse<RCVo> getRCbyUserId(String userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return CommonResponse.createForSuccessMessages("没有该ID的user");
        }
        Farmer farmer = farmerMapper.selectById(userId);
        if (farmer == null) {
            return CommonResponse.createForSuccessMessages("该用户不是farmer，没有加入合作社");
        }
        else if(farmer.getRcId().isEmpty()){
            return CommonResponse.createForSuccessMessages("该用户是farmer，但是没有加入合作社");
        }
        RC rc = rcMapper.selectById(farmer.getRcId());
        if (rc == null){
            return CommonResponse.createForSuccessMessages("没有该ID的rc");
        }
        return CommonResponse.createForSuccess(RCtoRCVo(rc));
    }

    private RCVo RCtoRCVo(RC rc) {
        RCVo rcVo = new RCVo();
        rcVo.setRcid(rc.getRcid());
        rcVo.setAddress(rc.getAddress());
        rcVo.setName(rc.getName());
        rcVo.setLand(rc.getLand());
        rcVo.setPond(rc.getPond());
        rcVo.setForest(rc.getForest());
        rcVo.setHead(rc.getHead());
        rcVo.setDescription(rc.getDescription());
        rcVo.setFarmerNumber(rc.getFarmerNumber());
        rcVo.setSwiper1(rc.getSwiper1());
        rcVo.setSwiper2(rc.getSwiper2());
        rcVo.setSwiper3(rc.getSwiper3());
        rcVo.setDescriptionImage(rc.getDescriptionImage());

        //找到UserId
        QueryWrapper<Farmer> farmerQueryWrapper = new QueryWrapper<>();
        farmerQueryWrapper.eq("rcId", rc.getRcid());
        List<Farmer> farmerList = farmerMapper.selectList(farmerQueryWrapper);
        List<String> userIdList = new ArrayList<>();
        for (Farmer item : farmerList) {
            String userId = item.getUserId();
            userIdList.add(userId);
        }
        String rcVoUserId;
        for (String item : userIdList) {
            User user = userMapper.selectById(item);
            if (user.getRole() == 2) {
                rcVoUserId = user.getUserId();
                rcVo.setUserId(rcVoUserId);
                //得到对应user的属性
                rcVo.setTelephone(user.getTelephone());
                rcVo.setAge(user.getAge());
                rcVo.setUserhead(user.getHead());
            }
        }
        return rcVo;
    }
}
